package com.jims.api.handler;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jims.master.common.constants.ExceptionCode;
import com.jims.master.common.constants.MsgStatus;
import com.jims.master.common.data.Message;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyExceptionHandler implements HandlerExceptionResolver {

	private Logger log = Logger.getLogger(MyExceptionHandler.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj,
			Exception ex) {
		
		Message message = null;

		ModelAndView mv = new ModelAndView();
		
		// 异常处理
		if (ex instanceof BizException) {
			BizException be = (BizException) ex;
			message = new Message(MsgStatus.FAILURE,be.getErrCode(),be.getErrMsg(),"");
			log.error(message.getErrCode(), ex.getCause());
		} else {
			message = new Message(MsgStatus.FAILURE, ExceptionCode.SERVICE_INNER_ERROR, ExceptionCode.SERVICE_INNER_ERROR_MSG);
			log.fatal(message.getErrCode()+",[ UnknownException:"+ex.getMessage()+" ]",ex.getCause());
		}
		message = new Message(MsgStatus.FAILURE, ExceptionCode.SERVICE_INNER_ERROR, ExceptionCode.SERVICE_INNER_ERROR_MSG);
		log.fatal(message.getErrCode()+",[ UnknownException:"+ex.getMessage()+" ]",ex.getCause());
		String msg = JSONObject.toJSONString(message,SerializerFeature.WriteMapNullValue);
		ex.printStackTrace();
		try {
			response.setContentType("text/html;charset=utf-8");
			response.getWriter().write(msg);

		} catch (IOException e) {
			log.fatal("ResponseWriteException:"+e.getMessage(), e.getCause());
			e.printStackTrace();
		}

		return mv;

	}

}
